package com.threeti.mecool.web.controller.report;

import static com.threeti.mecool.core.domain.model.basicdata.biz.MeCoolAdminDivisionAreaRegistry.customAreaRegistry;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.threeti.mecool.core.application.acl.UserService;
import com.threeti.mecool.core.application.project.ProjectService;
import com.threeti.mecool.core.application.report.ReportService;
import com.threeti.mecool.core.application.report.TaskPerformanceRate;
import com.threeti.mecool.core.domain.model.basicdata.AdminDivisionLevelDeep;
import com.threeti.mecool.core.domain.model.basicdata.biz.MeCoolAdminDivisionAreaRegistry;
import com.threeti.mecool.core.domain.model.plan.PlanJobResult;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultRepository;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.legacy.domain.model.basicdata.AdminDivisionLegacy;
import com.threeti.mecool.legacy.infrastructure.persistence.AdminDivisionLegacyRepository;
import com.threeti.mecool.web.util.RequestUtil;

@Controller
@RequestMapping("/report/taskPerformanceRate")
public class TaskPerformanceRateReportController {

	public static final Logger logger = LoggerFactory.getLogger(TaskPerformanceRateReportController.class);

	@Autowired
	private PlanJobResultRepository planJobResultRepo;

	@Autowired
	private ReportService rptService;

	@Autowired
	private AdminDivisionLegacyRepository adminDivLegRepo;

	@Autowired
	private AdminDivisionLegacyRepository adminDivisionLegacyRepository;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ProjectService projectService;
	
	@SuppressWarnings("unchecked")
	private void basicData(Map modelMap){
		modelMap.put("provinceList",adminDivisionLegacyRepository.findByDeep(1));
		modelMap.put("projectList", projectService.findProjectBasicInfoByUserPermission(userService.getUserFromSession()));
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			modelMap.put("customArea",mapper.writeValueAsString(customAreaRegistry()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/taskPerformanceReport.html")
	public void reportList(Map modelMap) {
		basicData(modelMap);
		
	}
	
	
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/{adminDivLevelDeep}.html")
	public String reportList(@PathVariable int adminDivLevelDeep, Map modelMap,HttpServletRequest request) {
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
		modelMap.putAll(RequestUtil.getParameterMap(request));
		return "/report/taskPerformanceRate/reportList";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/6/{customAdminDivAreaCode}.html")
	public String reportList1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);
		modelMap.putAll(RequestUtil.getParameterMap(request));
		return "/report/taskPerformanceRate/reportList";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/1/{standardAdminDivAreaCode}.html")
	public String reportList2(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {

		// 将异步操作转化为同步操作以满足地图绘制...
		List<TaskPerformanceRate> rates = rptService.taskPerformanceRateSummaryByProvince(standardAdminDivAreaCode);
		boolean isAreaNameSpecial = false;

		if (!CollectionUtils.isEmpty(rates)) {
			String tryingFirstRateAreaName = rates.get(0).getAdminDivAreaName();

			// 收到继续向下钻取的信号(目前即钻取至最明细级别的数据)
			if (isAreaNameSpecial = MeCoolAdminDivisionAreaRegistry.isAreaNameSpecial(tryingFirstRateAreaName)) {
				rates = rptService.taskPerformanceRateSummaryByCity(standardAdminDivAreaCode);
			}
		}

		modelMap.put("taskPerformanceRates", rates);// 汇总数据

		// jay:过于简单粗暴的处理方式，为了避免设置'城市or省市'这个标志位，处理为先根据城市查询,获取不到则尝试再获取省市数据，本处理差不多是以浪费一次查询为代价的
		// jay:Extract service and method...
		List<PlanJobResult> plannedTasksDetail;
		List<PlanJobResult> actualTasksDetail;
		try {
			plannedTasksDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_NOT_FINISHED,standardAdminDivAreaCode);
			actualTasksDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_FINISHED,standardAdminDivAreaCode);

			if (CollectionUtils.isEmpty(plannedTasksDetail)) {
				plannedTasksDetail = planJobResultRepo.findByJobStatusAndChannelChannelProvinceAdCode(PlanJobResult.JOB_STATUS_NOT_FINISHED,standardAdminDivAreaCode);
				actualTasksDetail = planJobResultRepo.findByJobStatusAndChannelChannelProvinceAdCode(PlanJobResult.JOB_STATUS_FINISHED,standardAdminDivAreaCode);

				// 计划门店和实际门店均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
				if (CollectionUtils.isEmpty(plannedTasksDetail)) {
					AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
					String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentProvinceAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentProvinceAdName();
					modelMap.put("standardAdminDivAreaName", provinceAdName);
				} else {
					modelMap.put("standardAdminDivAreaName", plannedTasksDetail.get(0).getStoreChannelProvinceAdName());
				}
				// <-
				if (isAreaNameSpecial) {// 发现特殊地域名的，强制视为已经进入特定城市内部
					modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
					modelMap.put("mapZoomLevel", "13");// 13是一个相对合适的用于省市级别展示的ZOOM等级
				} else {
					modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.CITY.ordinal());
					modelMap.put("mapZoomLevel", "8");// 8是一个相对合适的用于省市级别展示的ZOOM等级
				}
			} else {
				modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
				modelMap.put("standardAdminDivAreaName", plannedTasksDetail.get(0).getStoreChannelCityAdName());
				modelMap.put("mapZoomLevel", "13");// 13是一个相对合适的用于城区级别展示的ZOOM等级
			}

			// 明细数据
			modelMap.put("actualTasksDetail", actualTasksDetail);
			modelMap.put("plannedTasksDetail", plannedTasksDetail);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// <-
		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);
		return "/report/taskPerformanceRate/reportListCityMap";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/2/{standardAdminDivAreaCode}.html")
	public String reportList3(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		List<TaskPerformanceRate> rates = rptService.taskPerformanceRateSummaryByCity(standardAdminDivAreaCode);

		modelMap.put("taskPerformanceRates", rates);// 汇总数据
		modelMap.put("mapZoomLevel", "13");// 13是一个相对合适的用于城区级别展示的ZOOM等级
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());

		try {
			List<PlanJobResult> plannedStoresDetail;
			List<PlanJobResult> actualStoresDetail;

			plannedStoresDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_NOT_FINISHED,standardAdminDivAreaCode);
			actualStoresDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_FINISHED,standardAdminDivAreaCode);

			// 计划任务和实际任务均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
			if (CollectionUtils.isEmpty(plannedStoresDetail)) {
				AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
				String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentCityAdName();
				modelMap.put("standardAdminDivAreaName", provinceAdName);
			} else {
				modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getStoreChannelCityAdName());
			}
			// <-

			// 明细数据
			modelMap.put("actualTasksDetail", actualStoresDetail);
			modelMap.put("plannedTasksDetail", plannedStoresDetail);
		} catch (Exception e) {
			e.printStackTrace();
		}

		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);

		return "/report/taskPerformanceRate/reportListCityMap";
	}

	/**
	 * 全国
	 * @author Yuqi Chou
	 * @param adminDivLevelDeep
	 * @param modelMap
	 * @param request
	 * @return
	 * @version Oct 30, 2012  11:05:51 AM
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportListData/{adminDivLevelDeep}.html")
	public String reportListData(@PathVariable int adminDivLevelDeep,Map modelMap,HttpServletRequest request) {
		
		
		Map paramMap = RequestUtil.getParameterMap(request);
		
		
		List<TaskPerformanceRate> rates = Lists.newArrayList();
		if (adminDivLevelDeep == AdminDivisionLevelDeep.NATIONWIDE.ordinal()) {
			rates.add(rptService.taskPerformanceRateSummaryByCountry());
		} else if (adminDivLevelDeep == AdminDivisionLevelDeep.PROVINCE.ordinal()) {
			rates = rptService.taskPerformanceRateSummaryByProvinceALL(paramMap);
			modelMap.put("taskPerformanceRatesNationwide",rptService.taskPerformanceRateSummaryByCountry());
		} else if (adminDivLevelDeep == AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal()) {
			rates = rptService.taskPerformanceRateSummaryByCustomAreas();
		}
		modelMap.put("taskPerformanceRates", rates);
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);

		return "/report/taskPerformanceRate/reportListData";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportListData/6/{customAdminDivAreaCode}.html")
	public String reportListData1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		//Map<String, String> paramMap = RequestUtil.getParameterMap(request);
		
		List<TaskPerformanceRate> rates = rptService.taskPerformanceRateSummaryByCustomArea(customAdminDivAreaCode);

		modelMap.put("taskPerformanceRates", rates);
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.PROVINCE.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);

		return "/report/taskPerformanceRate/reportListData";
	}
	
	
}
